package com.tc.dispatch.web.schedule.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.model.OrderSumMain;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.gsservice.model.ProcessStep;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.model.combinedOrder;
import com.tc.dispatch.web.util.DateJsonValueProcessor;

public class orderProcessAdd extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public orderProcessAdd() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		

		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();
		if (action.equals("list")) {
			/* 将所有的stepList显示出来 */

			List processList, processListDef;
			try {
				String start = request.getParameter("start");
				String limit = request.getParameter("limit");
				if (start == null)
					start = "0";
				if (limit == null)
					limit = "0";
				List ret = new ArrayList();
				String sort = request.getParameter("specName");
				String scheme = request.getParameter("scheme");
				String pos=request.getParameter("processPos");
				String processName=request.getParameter("processName");
				
				if(sort!=null)
				{
				String whereStr=" where ";
				if(sort==null||sort.equals(""))
				{
				}
				else
				{
					whereStr+=("specName='"+sort+"' and ");
				}
				if(scheme==null||scheme.equals(""))
				{}
				else
					whereStr+=("scheme="+scheme+" and ");
				if(pos==null||pos.equals(""))
				{}
				else
					whereStr+=("processPos="+pos+" and ");
				if(processName==null||processName.equals(""))
				{}
				else
					whereStr+=("processName='"+processName+"' and ");
				whereStr+=" 1=1 order by processPos";
				List sortList = gss.findProcessStep(whereStr);
				ret = sortList;
				}
				else
				{
				ret = gss.findProcessStepByPages(Integer.parseInt(start),
						Integer.parseInt(limit));
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(gss.getPSTotalNum("")));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (Exception e) {
				out.print("{success:false, data:'false'}");
			}
		} else if (action.equals("sortList")) {
			try {

				List ret = gss.findProcessStep("");
				Iterator it = ret.iterator();
				ProcessStep ps;
				List retList = new ArrayList();
				Iterator it2 = retList.iterator();
				boolean flag=false;
				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					it2 = retList.iterator();
					flag=false;
					while (it2.hasNext()) {
						if (ps.getSpecName().equals(
								((ProcessStep) it2.next()).getSpecName()))
						{
							flag=true;
							break;
						}
					}
					if (!flag)
						{
					
						retList.add(ps);
						}
					
				}
				//System.out.println(retList.size());
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(retList.size()));

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (Exception e) {
				System.out.println(e.getMessage());
				out.print("{success:false, data:'false'}");
			}
		} else if (action.equals("schemeList")) {
			try {
				String sort = request.getParameter("specName");
				List sortList = gss.findProcessStep(" where specName='" + sort
						+ "'");
				Iterator it = sortList.iterator();
				ProcessStep ps;
				List ret = new ArrayList();
				List retList = new ArrayList();
				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					if (ret.indexOf(new Integer(ps.getScheme())) < 0) {
						ret.add(new Integer(ps.getScheme()));
						retList.add(ps);
					}
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("root", arr);
				// json.

				response.getWriter().print(json);
			} catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}
		} else if (action.equals("processNameList")) {
			try {
				String sort = request.getParameter("specName");
				String scheme = request.getParameter("scheme");
				List sortList = gss.findProcessStep(" where specName='" + sort
						+ "' and scheme=" + scheme+" order by processPos");
				List ret = sortList;
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}
		}else if (action.equals("add")) {
			try{
			String specName = request.getParameter("specName");
			String scheme = request.getParameter("scheme");
			String processName = request.getParameter("processName");
			String processPos = request.getParameter("processPos");
			String bz = request.getParameter("bz");
			String date1 = request.getParameter("date1");
			String areaFunc=request.getParameter("areaFunc");
			/*按道理说需要增加检验的 ，现在都放在页面中处理*/
			ProcessStep ps = new ProcessStep(0, specName, Integer
					.parseInt(scheme), processName, Integer
					.parseInt(processPos), bz, new Date(),areaFunc);
			gss.createProcessStep(ps);
			}
			catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}
			catch (Exception e) {
				System.out.println("exception in add "+e.getMessage());
				out.print("{success:false, data:'false'}");
			}
			
		}

		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
